<template>
  <div class="order-list-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>订单列表</span>
        </div>
      </template>

      <div class="search-box">
        <el-form :inline="true" :model="queryParams" class="demo-form-inline">
          <el-form-item label="订单号">
            <el-input
              v-model="queryParams.order_no"
              placeholder="请输入订单号"
              clearable
            />
          </el-form-item>
          <el-form-item label="用户账号">
            <el-input
              v-model="queryParams.username"
              placeholder="请输入用户账号"
              clearable
            />
          </el-form-item>
          <el-form-item label="状态">
            <el-select
              v-model="queryParams.status"
              placeholder="请选择状态"
              clearable
            >
              <el-option label="待支付" value="PENDING" />
              <el-option label="已支付" value="PAID" />
              <el-option label="已取消" value="CLOSED" />
              <el-option label="已退款" value="REFUNDED" />
            </el-select>
          </el-form-item>

          <el-form-item label="支付平台">
            <el-select
              v-model="queryParams.platform_type"
              placeholder="请选择支付平台"
              clearable
            >
              <el-option label="小程序" :value="MP" />
              <el-option label="公众号" :value="H5" />
            </el-select>
          </el-form-item>

          <el-form-item label="时间范围">
            <el-date-picker
              v-model="dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="YYYY-MM-DD"
              @change="handleDateChange"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleQuery">查询</el-button>
            <el-button @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <div class="statistics-box" v-if="statistics.total_amount">
        <el-descriptions :column="4" border>
          <el-descriptions-item label="订单总数">{{
            statistics.total_count
          }}</el-descriptions-item>
          <el-descriptions-item label="成交总额"
            >¥{{ statistics.total_amount }}</el-descriptions-item
          >
          <el-descriptions-item label="待支付">{{
            statistics.unpaid_count
          }}</el-descriptions-item>
          <el-descriptions-item label="已支付">{{
            statistics.paid_count
          }}</el-descriptions-item>
        </el-descriptions>
      </div>

      <el-table
        style="width: 1000%; margin: auto"
        v-loading="loading"
        :data="orderList"
      >
        <el-table-column prop="id" label="订单ID" width="180" />
        <el-table-column prop="user_id" label="支付用户ID" width="120" />
        <el-table-column
          prop="user.nick_name"
          label="支付用户账号"
          width="120"
        />
        <!-- <el-table-column label="用户手机" width="120">
          <template #default="scope">
            {{
              scope.row.user && scope.row.user.mobile
                ? userStore.isTest
                  ? maskMobile(scope.row.user.mobile)
                  : scope.row.user.mobile
                : ""
            }}
          </template>
        </el-table-column> -->
        <el-table-column prop="plan.name" label="套餐名称" width="120" />
        <el-table-column prop="amount" label="金额" width="100">
          <template #default="scope"> {{ scope.row.amount }} </template>
        </el-table-column>
        <el-table-column prop="total_fee" label="实际支付金额" width="120">
          <template #default="scope"> {{ scope.row.total_fee }} /分 </template>
        </el-table-column>
        <el-table-column label="支付方式" width="140">
          <template #default="scope">
            {{ getPayTypeName(scope.row.payment?.payment_type) }}
          </template>
        </el-table-column>
        <el-table-column prop="platform_type" label="支付平台" width="100">
          <template #default="scope">
            {{ getPlatformTypeName(scope.row.platform_type) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ getStatusName(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="create_time" label="创建时间" width="180" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button size="small" @click="handleDetail(scope.row)"
              >详情</el-button
            >
            <el-button
              size="small"
              type="primary"
              v-if="scope.row.status === 0"
              @click="handleConfirmPayment(scope.row)"
            >
              确认支付
            </el-button>
            <el-button
              size="small"
              type="warning"
              v-if="scope.row.status === 1"
              @click="handleRefund(scope.row)"
            >
              退款
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          :current-page="queryParams.page"
          :page-size="queryParams.limit"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import { useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  getOrderList,
  updateOrderStatus,
  confirmOrderPayment,
  getOrderStatistics,
} from "@/api/orders";
import { useUserStore } from "@/store/user";

const router = useRouter();
const userStore = useUserStore();
const loading = ref(false);
const orderList = ref([]);
const total = ref(0);
const dateRange = ref([]);
const statistics = ref({
  total_count: 0,
  total_amount: 0,
  unpaid_count: 0,
  paid_count: 0,
});

const queryParams = reactive({
  page: 1,
  limit: 10,
  order_no: "",
  username: "",
  status: "",
  start_date: "",
  end_date: "",
});

// 获取订单列表
const getList = async () => {
  loading.value = true;
  try {
    const res = await getOrderList(queryParams);
    if (res.code === 0) {
      orderList.value = res.data.items;
      total.value = res.data.total;
    } else {
      ElMessage.error(res.message || "获取订单列表失败");
    }
  } catch (error) {
    console.error("获取订单列表失败", error);
    ElMessage.error("获取订单列表失败");
  } finally {
    loading.value = false;
  }
};

// 获取订单统计数据
const getStatistics = async () => {
  try {
    const res = await getOrderStatistics({
      start_date: queryParams.start_date,
      end_date: queryParams.end_date,
    });
    if (res.code === 0) {
      statistics.value = res.data;
    }
  } catch (error) {
    console.error("获取订单统计失败", error);
  }
};

// 查询
const handleQuery = () => {
  queryParams.page = 1;
  getList();
  getStatistics();
};

// 重置查询
const resetQuery = () => {
  queryParams.order_no = "";
  queryParams.username = "";
  queryParams.status = "";
  queryParams.start_date = "";
  queryParams.end_date = "";
  dateRange.value = [];
  handleQuery();
};

// 日期范围变化
const handleDateChange = (val) => {
  if (val) {
    queryParams.start_date = val[0];
    queryParams.end_date = val[1];
  } else {
    queryParams.start_date = "";
    queryParams.end_date = "";
  }
};

// 页码改变
const handleCurrentChange = (val) => {
  queryParams.page = val;
  getList();
};

// 每页条数改变
const handleSizeChange = (val) => {
  queryParams.limit = val;
  queryParams.page = 1;
  getList();
};

// 查看详情
const handleDetail = (row) => {
  router.push(`/order/detail/${row.id}`);
};

// 确认支付
const handleConfirmPayment = (row) => {
  // 检查权限
  if (userStore.isTest) {
    ElMessage.warning("测试账号不能执行确认支付操作");
    return;
  }

  ElMessageBox.confirm(
    `确认要将订单 "${row.order_no}" 标记为已支付吗?`,
    "提示",
    {
      confirmButtonText: "确认",
      cancelButtonText: "取消",
      type: "warning",
    }
  )
    .then(async () => {
      try {
        const res = await confirmOrderPayment(row.id);
        if (res.code === 0) {
          ElMessage.success("操作成功");
          getList();
          getStatistics();
        } else {
          ElMessage.error(res.message || "操作失败");
        }
      } catch (error) {
        console.error("操作失败", error);
        ElMessage.error("操作失败");
      }
    })
    .catch(() => {
      // 取消操作
    });
};

// 退款操作
const handleRefund = (row) => {
  // 检查权限
  if (userStore.isTest) {
    ElMessage.warning("测试账号不能执行退款操作");
    return;
  }

  ElMessageBox.confirm(
    `确认要对订单 "${row.order_no}" 进行退款操作吗?`,
    "提示",
    {
      confirmButtonText: "确认",
      cancelButtonText: "取消",
      type: "warning",
    }
  )
    .then(async () => {
      try {
        const res = await updateOrderStatus(row.id, 3);
        if (res.code === 0) {
          ElMessage.success("退款操作成功");
          getList();
          getStatistics();
        } else {
          ElMessage.error(res.message || "操作失败");
        }
      } catch (error) {
        console.error("操作失败", error);
        ElMessage.error("操作失败");
      }
    })
    .catch(() => {
      // 取消操作
    });
};

/**
 * 获取支付方式中文名称
 * @param {string} type - 支付方式代码，如 WXPAY、ALIPAY 等
 * @returns {string} 支付方式中文名称，未知则返回“未知”
 */
const getPayTypeName = (type) => {
  const payTypes = {
    WXPAY: "微信支付",
    ALIPAY: "支付宝支付",
    OTHERS: "微信零钱", // 兼容旧字段
    CMB_DEBIT: "招商银行借记卡",
    COMM_DEBIT: "交通银行借记卡",
    ICBC_DEBIT: "工商银行借记卡",
    ABC_DEBIT: "农业银行借记卡",
    BOC_DEBIT: "中国银行借记卡",
    CCB_DEBIT: "建设银行借记卡",
    SPDB_DEBIT: "浦发银行借记卡",
    BOC_CREDIT: "中国银行信用卡",
    ALIPAY_CREDIT: "支付宝信用卡",
    UNIONPAY: "银联支付",
    UNIONPAY_CREDIT: "银联信用卡",
    UNIONPAY_DEBIT: "银联借记卡",
    JD_PAY: "京东支付",
    JD_CREDIT: "京东白条",
    JD_DEBIT: "京东借记卡",
    QQ_WALLET: "QQ钱包",
    JD_WALLET: "京东钱包",
    WECHAT_WALLET: "微信钱包",
    BILIBILI: "哔哩哔哩支付",
    TOUTIAO: "今日头条支付",
    KUAISHOU: "快手支付",
    DOUYIN: "抖音支付",
    MEITUAN: "美团支付",
    DINGDING: "钉钉支付",
    BAIDU: "百度支付",
    ALIPAY_WALLET: "支付宝钱包",
    ALIPAY_QR: "支付宝扫码支付",
    WXPAY_QR: "微信扫码支付",
    WXPAY_APP: "微信APP支付",
    ALIPAY_APP: "支付宝APP支付",
    ALIPAY_WAP: "支付宝手机网页支付",
    WXPAY_WAP: "微信手机网页支付",
    ALIPAY_SCAN: "支付宝扫码支付",
    WXPAY_SCAN: "微信扫码支付",
    ALIPAY_TRANSFER: "支付宝转账",
    WXPAY_TRANSFER: "微信转账",
    ALIPAY_INVOICE: "支付宝发票",
    WXPAY_INVOICE: "微信发票",
    ALIPAY_QRCODE: "支付宝二维码支付",
    WXPAY_QRCODE: "微信二维码支付",
    ALIPAY_OFFLINE: "支付宝线下支付",
    WXPAY_OFFLINE: "微信线下支付",
    ALIPAY_POS: "支付宝POS机支付",
    WXPAY_POS: "微信POS机支付",
    ALIPAY_MOBILE: "支付宝手机支付",
    WXPAY_MOBILE: "微信手机支付",
    ALIPAY_WEB: "支付宝网页支付",
    WXPAY_WEB: "微信网页支付",
    ALIPAY_APP_QR: "支付宝APP扫码支付",
    WXPAY_APP_QR: "微信APP扫码支付",
    ALIPAY_WAP_QR: "支付宝手机网页扫码支付",
    WXPAY_WAP_QR: "微信手机网页扫码支付",
    ALIPAY_WALLET_QR: "支付宝钱包扫码支付",
    WXPAY_WALLET_QR: "微信钱包扫码支付",
    ALIPAY_QR_CODE: "支付宝二维码支付",
    WXPAY_QR_CODE: "微信二维码支付",
    ALIPAY_OFFLINE_QR: "支付宝线下二维码支付",
    WXPAY_OFFLINE_QR: "微信线下二维码支付",
    ALIPAY_POS_QR: "支付宝POS机二维码支付",
    WXPAY_POS_QR: "微信POS机二维码支付",
    ALIPAY_MOBILE_QR: "支付宝手机二维码支付",
    PAYPAL: "PayPal支付",
  };

  if (typeof type !== "string") return "未知";

  // 支持大小写转换
  return payTypes[type.toUpperCase()] || "未知";
};

const getPlatformTypeName = (type) => {
  const platformTypes = {
    MP: "小程序",
    H5: "公众号",
  };
  return platformTypes[type] || "未知";
};

// 获取状态名称
const getStatusName = (status) => {
  const statusMap = {
    PENDING: "待支付",
    PAID: "已支付",
    CLOSED: "已取消",
    3: "已退款",
  };
  return statusMap[status] || "未知";
};
// 获取状态对应的标签类型
const getStatusType = (status) => {
  const statusTypeMap = {
    PENDING: "待支付",
    PAID: "已支付",
    CLOSED: "已关闭",
  };
  return statusTypeMap[status] || "";
};

// 手机号脱敏处理
const maskMobile = (mobile) => {
  if (!mobile) return "";
  return mobile.replace(/^(\d{3})\d{4}(\d{4})$/, "$1****$2");
};

onMounted(() => {
  getList();
  getStatistics();
});
</script>

<style scoped>
.order-list-container {
  height: 100%;
  padding: 20px;
}

.box-card {
  height: 100%;
  display: flex;
  flex-direction: column;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-box {
  margin-bottom: 20px;
  background: #f9fafc;
  padding: 16px;
  border-radius: 8px;
}

.statistics-box {
  margin-bottom: 20px;
  background: #f9fafc;
  padding: 16px;
  border-radius: 8px;
}

.el-table {
  flex: 1;
  border-radius: 8px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

/* 表格内容样式优化 */
:deep(.el-table td) {
  padding: 12px 0;
}

:deep(.el-table .cell) {
  line-height: 1.5;
}

/* 按钮样式调整 */
.card-header .el-button {
  padding: 9px 16px;
}

.el-table .el-button {
  padding: 6px 12px;
  margin: 0 4px;
}

.el-tag {
  font-weight: 500;
}
</style>
